home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / pymodules / python2.6 / configobj.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-11-02  |  66.3 KB  |  2,175 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. from __future__ import generators
  5. import sys
  6. INTP_VER = sys.version_info[:2]
  7. if INTP_VER < (2, 2):
  8.     raise RuntimeError('Python v.2.2 or later needed')
  9. INTP_VER < (2, 2)
  10. import os
  11. import re
  12. compiler = None
  13.  
  14. try:
  15.     import compiler
  16. except ImportError:
  17.     pass
  18.  
  19. from types import StringTypes
  20. from warnings import warn
  21.  
  22. try:
  23.     from codecs import BOM_UTF8, BOM_UTF16, BOM_UTF16_BE, BOM_UTF16_LE
  24. except ImportError:
  25.     BOM_UTF8 = '\xef\xbb\xbf'
  26.     BOM_UTF16_LE = '\xff\xfe'
  27.     BOM_UTF16_BE = '\xfe\xff'
  28.     if sys.byteorder == 'little':
  29.         BOM_UTF16 = BOM_UTF16_LE
  30.     else:
  31.         BOM_UTF16 = BOM_UTF16_BE
  32. except:
  33.     sys.byteorder == 'little'
  34.  
  35. BOMS = {
  36.     BOM_UTF8: ('utf_8', None),
  37.     BOM_UTF16_BE: ('utf16_be', 'utf_16'),
  38.     BOM_UTF16_LE: ('utf16_le', 'utf_16'),
  39.     BOM_UTF16: ('utf_16', 'utf_16') }
  40. BOM_LIST = {
  41.     'utf_16': 'utf_16',
  42.     'u16': 'utf_16',
  43.     'utf16': 'utf_16',
  44.     'utf-16': 'utf_16',
  45.     'utf16_be': 'utf16_be',
  46.     'utf_16_be': 'utf16_be',
  47.     'utf-16be': 'utf16_be',
  48.     'utf16_le': 'utf16_le',
  49.     'utf_16_le': 'utf16_le',
  50.     'utf-16le': 'utf16_le',
  51.     'utf_8': 'utf_8',
  52.     'u8': 'utf_8',
  53.     'utf': 'utf_8',
  54.     'utf8': 'utf_8',
  55.     'utf-8': 'utf_8' }
  56. BOM_SET = {
  57.     'utf_8': BOM_UTF8,
  58.     'utf_16': BOM_UTF16,
  59.     'utf16_be': BOM_UTF16_BE,
  60.     'utf16_le': BOM_UTF16_LE,
  61.     None: BOM_UTF8 }
  62.  
  63. def match_utf8(encoding):
  64.     return BOM_LIST.get(encoding.lower()) == 'utf_8'
  65.  
  66. squot = "'%s'"
  67. dquot = '"%s"'
  68. noquot = '%s'
  69. wspace_plus = ' \r\t\n\x0b\t\'"'
  70. tsquot = '"""%s"""'
  71. tdquot = "'''%s'''"
  72.  
  73. try:
  74.     enumerate
  75. except NameError:
  76.     
  77.     def enumerate(obj):
  78.         '''enumerate for Python 2.2.'''
  79.         i = -1
  80.         for item in obj:
  81.             i += 1
  82.             yield (i, item)
  83.         
  84.  
  85.  
  86.  
  87. try:
  88.     (True, False)
  89. except NameError:
  90.     (True, False) = (1, 0)
  91.  
  92. __version__ = '4.5.3'
  93. __revision__ = '$Id: configobj.py 156 2006-01-31 14:57:08Z fuzzyman $'
  94. __docformat__ = 'restructuredtext en'
  95. __all__ = ('__version__', 'DEFAULT_INDENT_TYPE', 'DEFAULT_INTERPOLATION', 'ConfigObjError', 'NestingError', 'ParseError', 'DuplicateError', 'ConfigspecError', 'ConfigObj', 'SimpleVal', 'InterpolationError', 'InterpolationLoopError', 'MissingInterpolationOption', 'RepeatSectionError', 'ReloadError', 'UnreprError', 'UnknownType', '__docformat__', 'flatten_errors')
  96. DEFAULT_INTERPOLATION = 'configparser'
  97. DEFAULT_INDENT_TYPE = '    '
  98. MAX_INTERPOL_DEPTH = 10
  99. OPTION_DEFAULTS = {
  100.     'interpolation': True,
  101.     'raise_errors': False,
  102.     'list_values': True,
  103.     'create_empty': False,
  104.     'file_error': False,
  105.     'configspec': None,
  106.     'stringify': True,
  107.     'indent_type': None,
  108.     'encoding': None,
  109.     'default_encoding': None,
  110.     'unrepr': False,
  111.     'write_empty_values': False }
  112.  
  113. def getObj(s):
  114.     s = 'a=' + s
  115.     if compiler is None:
  116.         raise ImportError('compiler module not available')
  117.     compiler is None
  118.     p = compiler.parse(s)
  119.     return p.getChildren()[1].getChildren()[0].getChildren()[1]
  120.  
  121.  
  122. class UnknownType(Exception):
  123.     pass
  124.  
  125.  
  126. class Builder(object):
  127.     
  128.     def build(self, o):
  129.         m = getattr(self, 'build_' + o.__class__.__name__, None)
  130.         if m is None:
  131.             raise UnknownType(o.__class__.__name__)
  132.         m is None
  133.         return m(o)
  134.  
  135.     
  136.     def build_List(self, o):
  137.         return map(self.build, o.getChildren())
  138.  
  139.     
  140.     def build_Const(self, o):
  141.         return o.value
  142.  
  143.     
  144.     def build_Dict(self, o):
  145.         d = { }
  146.         i = iter(map(self.build, o.getChildren()))
  147.         for el in i:
  148.             d[el] = i.next()
  149.         
  150.         return d
  151.  
  152.     
  153.     def build_Tuple(self, o):
  154.         return tuple(self.build_List(o))
  155.  
  156.     
  157.     def build_Name(self, o):
  158.         if o.name == 'None':
  159.             return None
  160.         if o.name == 'True':
  161.             return True
  162.         if o.name == 'False':
  163.             return False
  164.         raise UnknownType('Undefined Name')
  165.  
  166.     
  167.     def build_Add(self, o):
  168.         (real, imag) = map(self.build_Const, o.getChildren())
  169.         
  170.         try:
  171.             real = float(real)
  172.         except TypeError:
  173.             raise UnknownType('Add')
  174.  
  175.         if not isinstance(imag, complex) or imag.real != 0:
  176.             raise UnknownType('Add')
  177.         imag.real != 0
  178.         return real + imag
  179.  
  180.     
  181.     def build_Getattr(self, o):
  182.         parent = self.build(o.expr)
  183.         return getattr(parent, o.attrname)
  184.  
  185.     
  186.     def build_UnarySub(self, o):
  187.         return -self.build_Const(o.getChildren()[0])
  188.  
  189.     
  190.     def build_UnaryAdd(self, o):
  191.         return self.build_Const(o.getChildren()[0])
  192.  
  193.  
  194. _builder = Builder()
  195.  
  196. def unrepr(s):
  197.     if not s:
  198.         return s
  199.     return _builder.build(getObj(s))
  200.  
  201.  
  202. class ConfigObjError(SyntaxError):
  203.     '''
  204.     This is the base class for all errors that ConfigObj raises.
  205.     It is a subclass of SyntaxError.
  206.     '''
  207.     
  208.     def __init__(self, message = '', line_number = None, line = ''):
  209.         self.line = line
  210.         self.line_number = line_number
  211.         self.message = message
  212.         SyntaxError.__init__(self, message)
  213.  
  214.  
  215.  
  216. class NestingError(ConfigObjError):
  217.     """
  218.     This error indicates a level of nesting that doesn't match.
  219.     """
  220.     pass
  221.  
  222.  
  223. class ParseError(ConfigObjError):
  224.     '''
  225.     This error indicates that a line is badly written.
  226.     It is neither a valid ``key = value`` line,
  227.     nor a valid section marker line.
  228.     '''
  229.     pass
  230.  
  231.  
  232. class ReloadError(IOError):
  233.     """
  234.     A 'reload' operation failed.
  235.     This exception is a subclass of ``IOError``.
  236.     """
  237.     
  238.     def __init__(self):
  239.         IOError.__init__(self, 'reload failed, filename is not set.')
  240.  
  241.  
  242.  
  243. class DuplicateError(ConfigObjError):
  244.     '''
  245.     The keyword or section specified already exists.
  246.     '''
  247.     pass
  248.  
  249.  
  250. class ConfigspecError(ConfigObjError):
  251.     '''
  252.     An error occured whilst parsing a configspec.
  253.     '''
  254.     pass
  255.  
  256.  
  257. class InterpolationError(ConfigObjError):
  258.     '''Base class for the two interpolation errors.'''
  259.     pass
  260.  
  261.  
  262. class InterpolationLoopError(InterpolationError):
  263.     '''Maximum interpolation depth exceeded in string interpolation.'''
  264.     
  265.     def __init__(self, option):
  266.         InterpolationError.__init__(self, 'interpolation loop detected in value "%s".' % option)
  267.  
  268.  
  269.  
  270. class RepeatSectionError(ConfigObjError):
  271.     '''
  272.     This error indicates additional sections in a section with a
  273.     ``__many__`` (repeated) section.
  274.     '''
  275.     pass
  276.  
  277.  
  278. class MissingInterpolationOption(InterpolationError):
  279.     '''A value specified for interpolation was missing.'''
  280.     
  281.     def __init__(self, option):
  282.         InterpolationError.__init__(self, 'missing option "%s" in interpolation.' % option)
  283.  
  284.  
  285.  
  286. class UnreprError(ConfigObjError):
  287.     '''An error parsing in unrepr mode.'''
  288.     pass
  289.  
  290.  
  291. class InterpolationEngine(object):
  292.     '''
  293.     A helper class to help perform string interpolation.
  294.  
  295.     This class is an abstract base class; its descendants perform
  296.     the actual work.
  297.     '''
  298.     _KEYCRE = re.compile('%\\(([^)]*)\\)s')
  299.     
  300.     def __init__(self, section):
  301.         self.section = section
  302.  
  303.     
  304.     def interpolate(self, key, value):
  305.         
  306.         def recursive_interpolate(key, value, section, backtrail):
  307.             """The function that does the actual work.
  308.  
  309.             ``value``: the string we're trying to interpolate.
  310.             ``section``: the section in which that string was found
  311.             ``backtrail``: a dict to keep track of where we've been,
  312.             to detect and prevent infinite recursion loops
  313.  
  314.             This is similar to a depth-first-search algorithm.
  315.             """
  316.             if backtrail.has_key((key, section.name)):
  317.                 raise InterpolationLoopError(key)
  318.             backtrail.has_key((key, section.name))
  319.             backtrail[(key, section.name)] = 1
  320.             match = self._KEYCRE.search(value)
  321.             while match:
  322.                 (k, v, s) = self._parse_match(match)
  323.                 if k is None:
  324.                     replacement = v
  325.                 else:
  326.                     replacement = recursive_interpolate(k, v, s, backtrail)
  327.                 (start, end) = match.span()
  328.                 value = ''.join((value[:start], replacement, value[end:]))
  329.                 new_search_start = start + len(replacement)
  330.                 match = self._KEYCRE.search(value, new_search_start)
  331.             del backtrail[(key, section.name)]
  332.             return value
  333.  
  334.         value = recursive_interpolate(key, value, self.section, { })
  335.         return value
  336.  
  337.     
  338.     def _fetch(self, key):
  339.         '''Helper function to fetch values from owning section.
  340.  
  341.         Returns a 2-tuple: the value, and the section where it was found.
  342.         '''
  343.         save_interp = self.section.main.interpolation
  344.         self.section.main.interpolation = False
  345.         current_section = self.section
  346.         while True:
  347.             val = current_section.get(key)
  348.             if val is not None:
  349.                 break
  350.             
  351.             val = current_section.get('DEFAULT', { }).get(key)
  352.             if val is not None:
  353.                 break
  354.             
  355.             if current_section.parent is current_section:
  356.                 break
  357.             
  358.             current_section = current_section.parent
  359.         self.section.main.interpolation = save_interp
  360.         if val is None:
  361.             raise MissingInterpolationOption(key)
  362.         val is None
  363.         return (val, current_section)
  364.  
  365.     
  366.     def _parse_match(self, match):
  367.         '''Implementation-dependent helper function.
  368.  
  369.         Will be passed a match object corresponding to the interpolation
  370.         key we just found (e.g., "%(foo)s" or "$foo"). Should look up that
  371.         key in the appropriate config file section (using the ``_fetch()``
  372.         helper function) and return a 3-tuple: (key, value, section)
  373.  
  374.         ``key`` is the name of the key we\'re looking for
  375.         ``value`` is the value found for that key
  376.         ``section`` is a reference to the section where it was found
  377.  
  378.         ``key`` and ``section`` should be None if no further
  379.         interpolation should be performed on the resulting value
  380.         (e.g., if we interpolated "$$" and returned "$").
  381.         '''
  382.         raise NotImplementedError()
  383.  
  384.  
  385.  
  386. class ConfigParserInterpolation(InterpolationEngine):
  387.     '''Behaves like ConfigParser.'''
  388.     _KEYCRE = re.compile('%\\(([^)]*)\\)s')
  389.     
  390.     def _parse_match(self, match):
  391.         key = match.group(1)
  392.         (value, section) = self._fetch(key)
  393.         return (key, value, section)
  394.  
  395.  
  396.  
  397. class TemplateInterpolation(InterpolationEngine):
  398.     '''Behaves like string.Template.'''
  399.     _delimiter = '$'
  400.     _KEYCRE = re.compile('\n        \\$(?:\n          (?P<escaped>\\$)              |   # Two $ signs\n          (?P<named>[_a-z][_a-z0-9]*)  |   # $name format\n          {(?P<braced>[^}]*)}              # ${name} format\n        )\n        ', re.IGNORECASE | re.VERBOSE)
  401.     
  402.     def _parse_match(self, match):
  403.         if not match.group('named'):
  404.             pass
  405.         key = match.group('braced')
  406.         if key is not None:
  407.             (value, section) = self._fetch(key)
  408.             return (key, value, section)
  409.         if match.group('escaped') is not None:
  410.             return (None, self._delimiter, None)
  411.         return (None, match.group(), None)
  412.  
  413.  
  414. interpolation_engines = {
  415.     'configparser': ConfigParserInterpolation,
  416.     'template': TemplateInterpolation }
  417.  
  418. class Section(dict):
  419.     """
  420.     A dictionary-like object that represents a section in a config file.
  421.     
  422.     It does string interpolation if the 'interpolation' attribute
  423.     of the 'main' object is set to True.
  424.     
  425.     Interpolation is tried first from this object, then from the 'DEFAULT'
  426.     section of this object, next from the parent and its 'DEFAULT' section,
  427.     and so on until the main object is reached.
  428.     
  429.     A Section will behave like an ordered dictionary - following the
  430.     order of the ``scalars`` and ``sections`` attributes.
  431.     You can use this to change the order of members.
  432.     
  433.     Iteration follows the order: scalars, then sections.
  434.     """
  435.     
  436.     def __init__(self, parent, depth, main, indict = None, name = None):
  437.         '''
  438.         * parent is the section above
  439.         * depth is the depth level of this section
  440.         * main is the main ConfigObj
  441.         * indict is a dictionary to initialise the section with
  442.         '''
  443.         if indict is None:
  444.             indict = { }
  445.         
  446.         dict.__init__(self)
  447.         self.parent = parent
  448.         self.main = main
  449.         self.depth = depth
  450.         self.name = name
  451.         self._initialise()
  452.         for entry, value in indict.iteritems():
  453.             self[entry] = value
  454.         
  455.  
  456.     
  457.     def _initialise(self):
  458.         self.scalars = []
  459.         self.sections = []
  460.         self.comments = { }
  461.         self.inline_comments = { }
  462.         self.configspec = { }
  463.         self._order = []
  464.         self._configspec_comments = { }
  465.         self._configspec_inline_comments = { }
  466.         self._cs_section_comments = { }
  467.         self._cs_section_inline_comments = { }
  468.         self.defaults = []
  469.         self.default_values = { }
  470.  
  471.     
  472.     def _interpolate(self, key, value):
  473.         
  474.         try:
  475.             engine = self._interpolation_engine
  476.         except AttributeError:
  477.             name = self.main.interpolation
  478.             if name == True:
  479.                 name = DEFAULT_INTERPOLATION
  480.             
  481.             name = name.lower()
  482.             class_ = interpolation_engines.get(name, None)
  483.             if class_ is None:
  484.                 self.main.interpolation = False
  485.                 return value
  486.         except:
  487.             engine = self._interpolation_engine = class_(self)
  488.  
  489.         return engine.interpolate(key, value)
  490.  
  491.     
  492.     def __getitem__(self, key):
  493.         '''Fetch the item and do string interpolation.'''
  494.         val = dict.__getitem__(self, key)
  495.         if self.main.interpolation and isinstance(val, StringTypes):
  496.             return self._interpolate(key, val)
  497.         return val
  498.  
  499.     
  500.     def __setitem__(self, key, value, unrepr = False):
  501.         """
  502.         Correctly set a value.
  503.         
  504.         Making dictionary values Section instances.
  505.         (We have to special case 'Section' instances - which are also dicts)
  506.         
  507.         Keys must be strings.
  508.         Values need only be strings (or lists of strings) if
  509.         ``main.stringify`` is set.
  510.         
  511.         `unrepr`` must be set when setting a value to a dictionary, without
  512.         creating a new sub-section.
  513.         """
  514.         if not isinstance(key, StringTypes):
  515.             raise ValueError('The key "%s" is not a string.' % key)
  516.         isinstance(key, StringTypes)
  517.         if not self.comments.has_key(key):
  518.             self.comments[key] = []
  519.             self.inline_comments[key] = ''
  520.         
  521.         if key in self.defaults:
  522.             self.defaults.remove(key)
  523.         
  524.         if isinstance(value, Section):
  525.             if not self.has_key(key):
  526.                 self.sections.append(key)
  527.             
  528.             dict.__setitem__(self, key, value)
  529.         elif isinstance(value, dict) and not unrepr:
  530.             if not self.has_key(key):
  531.                 self.sections.append(key)
  532.             
  533.             new_depth = self.depth + 1
  534.             dict.__setitem__(self, key, Section(self, new_depth, self.main, indict = value, name = key))
  535.         elif not self.has_key(key):
  536.             self.scalars.append(key)
  537.         
  538.         if not self.main.stringify:
  539.             if isinstance(value, StringTypes):
  540.                 pass
  541.             elif isinstance(value, (list, tuple)):
  542.                 for entry in value:
  543.                     if not isinstance(entry, StringTypes):
  544.                         raise TypeError('Value is not a string "%s".' % entry)
  545.                     isinstance(entry, StringTypes)
  546.                 
  547.             else:
  548.                 raise TypeError('Value is not a string "%s".' % value)
  549.         isinstance(value, StringTypes)
  550.         dict.__setitem__(self, key, value)
  551.  
  552.     
  553.     def __delitem__(self, key):
  554.         '''Remove items from the sequence when deleting.'''
  555.         dict.__delitem__(self, key)
  556.         if key in self.scalars:
  557.             self.scalars.remove(key)
  558.         else:
  559.             self.sections.remove(key)
  560.         del self.comments[key]
  561.         del self.inline_comments[key]
  562.  
  563.     
  564.     def get(self, key, default = None):
  565.         """A version of ``get`` that doesn't bypass string interpolation."""
  566.         
  567.         try:
  568.             return self[key]
  569.         except KeyError:
  570.             return default
  571.  
  572.  
  573.     
  574.     def update(self, indict):
  575.         '''
  576.         A version of update that uses our ``__setitem__``.
  577.         '''
  578.         for entry in indict:
  579.             self[entry] = indict[entry]
  580.         
  581.  
  582.     
  583.     def pop(self, key, *args):
  584.         """
  585.         'D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  586.         If key is not found, d is returned if given, otherwise KeyError is raised'
  587.         """
  588.         val = dict.pop(self, key, *args)
  589.         if key in self.scalars:
  590.             del self.comments[key]
  591.             del self.inline_comments[key]
  592.             self.scalars.remove(key)
  593.         elif key in self.sections:
  594.             del self.comments[key]
  595.             del self.inline_comments[key]
  596.             self.sections.remove(key)
  597.         
  598.         if self.main.interpolation and isinstance(val, StringTypes):
  599.             return self._interpolate(key, val)
  600.         return val
  601.  
  602.     
  603.     def popitem(self):
  604.         '''Pops the first (key,val)'''
  605.         sequence = self.scalars + self.sections
  606.         if not sequence:
  607.             raise KeyError(": 'popitem(): dictionary is empty'")
  608.         sequence
  609.         key = sequence[0]
  610.         val = self[key]
  611.         del self[key]
  612.         return (key, val)
  613.  
  614.     
  615.     def clear(self):
  616.         '''
  617.         A version of clear that also affects scalars/sections
  618.         Also clears comments and configspec.
  619.         
  620.         Leaves other attributes alone :
  621.             depth/main/parent are not affected
  622.         '''
  623.         dict.clear(self)
  624.         self.scalars = []
  625.         self.sections = []
  626.         self.comments = { }
  627.         self.inline_comments = { }
  628.         self.configspec = { }
  629.  
  630.     
  631.     def setdefault(self, key, default = None):
  632.         '''A version of setdefault that sets sequence if appropriate.'''
  633.         
  634.         try:
  635.             return self[key]
  636.         except KeyError:
  637.             self[key] = default
  638.             return self[key]
  639.  
  640.  
  641.     
  642.     def items(self):
  643.         """D.items() -> list of D's (key, value) pairs, as 2-tuples"""
  644.         return zip(self.scalars + self.sections, self.values())
  645.  
  646.     
  647.     def keys(self):
  648.         """D.keys() -> list of D's keys"""
  649.         return self.scalars + self.sections
  650.  
  651.     
  652.     def values(self):
  653.         """D.values() -> list of D's values"""
  654.         return [ self[key] for key in self.scalars + self.sections ]
  655.  
  656.     
  657.     def iteritems(self):
  658.         '''D.iteritems() -> an iterator over the (key, value) items of D'''
  659.         return iter(self.items())
  660.  
  661.     
  662.     def iterkeys(self):
  663.         '''D.iterkeys() -> an iterator over the keys of D'''
  664.         return iter(self.scalars + self.sections)
  665.  
  666.     __iter__ = iterkeys
  667.     
  668.     def itervalues(self):
  669.         '''D.itervalues() -> an iterator over the values of D'''
  670.         return iter(self.values())
  671.  
  672.     
  673.     def __repr__(self):
  674.         '''x.__repr__() <==> repr(x)'''
  675.         return [] % []([ '%s: %s' % (repr(key), repr(self[key])) for key in self.scalars + self.sections ])
  676.  
  677.     __str__ = __repr__
  678.     __str__.__doc__ = 'x.__str__() <==> str(x)'
  679.     
  680.     def dict(self):
  681.         '''
  682.         Return a deepcopy of self as a dictionary.
  683.         
  684.         All members that are ``Section`` instances are recursively turned to
  685.         ordinary dictionaries - by calling their ``dict`` method.
  686.         
  687.         >>> n = a.dict()
  688.         >>> n == a
  689.         1
  690.         >>> n is a
  691.         0
  692.         '''
  693.         newdict = { }
  694.         for entry in self:
  695.             this_entry = self[entry]
  696.             if isinstance(this_entry, Section):
  697.                 this_entry = this_entry.dict()
  698.             elif isinstance(this_entry, list):
  699.                 this_entry = list(this_entry)
  700.             elif isinstance(this_entry, tuple):
  701.                 this_entry = tuple(this_entry)
  702.             
  703.             newdict[entry] = this_entry
  704.         
  705.         return newdict
  706.  
  707.     
  708.     def merge(self, indict):
  709.         """
  710.         A recursive update - useful for merging config files.
  711.         
  712.         >>> a = '''[section1]
  713.         ...     option1 = True
  714.         ...     [[subsection]]
  715.         ...     more_options = False
  716.         ...     # end of file'''.splitlines()
  717.         >>> b = '''# File is user.ini
  718.         ...     [section1]
  719.         ...     option1 = False
  720.         ...     # end of file'''.splitlines()
  721.         >>> c1 = ConfigObj(b)
  722.         >>> c2 = ConfigObj(a)
  723.         >>> c2.merge(c1)
  724.         >>> c2
  725.         {'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}}
  726.         """
  727.         for key, val in indict.items():
  728.             if key in self and isinstance(self[key], dict) and isinstance(val, dict):
  729.                 self[key].merge(val)
  730.                 continue
  731.             self[key] = val
  732.         
  733.  
  734.     
  735.     def rename(self, oldkey, newkey):
  736.         '''
  737.         Change a keyname to another, without changing position in sequence.
  738.         
  739.         Implemented so that transformations can be made on keys,
  740.         as well as on values. (used by encode and decode)
  741.         
  742.         Also renames comments.
  743.         '''
  744.         if oldkey in self.scalars:
  745.             the_list = self.scalars
  746.         elif oldkey in self.sections:
  747.             the_list = self.sections
  748.         else:
  749.             raise KeyError('Key "%s" not found.' % oldkey)
  750.         pos = (oldkey in self.scalars).index(oldkey)
  751.         val = self[oldkey]
  752.         dict.__delitem__(self, oldkey)
  753.         dict.__setitem__(self, newkey, val)
  754.         the_list.remove(oldkey)
  755.         the_list.insert(pos, newkey)
  756.         comm = self.comments[oldkey]
  757.         inline_comment = self.inline_comments[oldkey]
  758.         del self.comments[oldkey]
  759.         del self.inline_comments[oldkey]
  760.         self.comments[newkey] = comm
  761.         self.inline_comments[newkey] = inline_comment
  762.  
  763.     
  764.     def walk(self, function, raise_errors = True, call_on_sections = False, **keywargs):
  765.         """
  766.         Walk every member and call a function on the keyword and value.
  767.         
  768.         Return a dictionary of the return values
  769.         
  770.         If the function raises an exception, raise the errror
  771.         unless ``raise_errors=False``, in which case set the return value to
  772.         ``False``.
  773.         
  774.         Any unrecognised keyword arguments you pass to walk, will be pased on
  775.         to the function you pass in.
  776.         
  777.         Note: if ``call_on_sections`` is ``True`` then - on encountering a
  778.         subsection, *first* the function is called for the *whole* subsection,
  779.         and then recurses into it's members. This means your function must be
  780.         able to handle strings, dictionaries and lists. This allows you
  781.         to change the key of subsections as well as for ordinary members. The
  782.         return value when called on the whole subsection has to be discarded.
  783.         
  784.         See  the encode and decode methods for examples, including functions.
  785.         
  786.         .. admonition:: Caution
  787.         
  788.             You can use ``walk`` to transform the names of members of a section
  789.             but you mustn't add or delete members.
  790.         
  791.         >>> config = '''[XXXXsection]
  792.         ... XXXXkey = XXXXvalue'''.splitlines()
  793.         >>> cfg = ConfigObj(config)
  794.         >>> cfg
  795.         {'XXXXsection': {'XXXXkey': 'XXXXvalue'}}
  796.         >>> def transform(section, key):
  797.         ...     val = section[key]
  798.         ...     newkey = key.replace('XXXX', 'CLIENT1')
  799.         ...     section.rename(key, newkey)
  800.         ...     if isinstance(val, (tuple, list, dict)):
  801.         ...         pass
  802.         ...     else:
  803.         ...         val = val.replace('XXXX', 'CLIENT1')
  804.         ...         section[newkey] = val
  805.         >>> cfg.walk(transform, call_on_sections=True)
  806.         {'CLIENT1section': {'CLIENT1key': None}}
  807.         >>> cfg
  808.         {'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}}
  809.         """
  810.         out = { }
  811.         for i in range(len(self.scalars)):
  812.             entry = self.scalars[i]
  813.             
  814.             try:
  815.                 val = function(self, entry, **keywargs)
  816.                 entry = self.scalars[i]
  817.                 out[entry] = val
  818.             continue
  819.             except Exception:
  820.                 if raise_errors:
  821.                     raise 
  822.                 raise_errors
  823.                 entry = self.scalars[i]
  824.                 out[entry] = False
  825.                 continue
  826.             
  827.  
  828.         
  829.         for i in range(len(self.sections)):
  830.             entry = self.sections[i]
  831.             if call_on_sections:
  832.                 
  833.                 try:
  834.                     function(self, entry, **keywargs)
  835.                 except Exception:
  836.                     None<EXCEPTION MATCH>Exception
  837.                     None<EXCEPTION MATCH>Exception
  838.                     if raise_errors:
  839.                         raise 
  840.                     raise_errors
  841.                     entry = self.sections[i]
  842.                     out[entry] = False
  843.                 except:
  844.                     None<EXCEPTION MATCH>Exception
  845.  
  846.                 entry = self.sections[i]
  847.             
  848.             out[entry] = self[entry].walk(function, raise_errors = raise_errors, call_on_sections = call_on_sections, **keywargs)
  849.         
  850.         return out
  851.  
  852.     
  853.     def decode(self, encoding):
  854.         """
  855.         Decode all strings and values to unicode, using the specified encoding.
  856.         
  857.         Works with subsections and list values.
  858.         
  859.         Uses the ``walk`` method.
  860.         
  861.         Testing ``encode`` and ``decode``.
  862.         >>> m = ConfigObj(a)
  863.         >>> m.decode('ascii')
  864.         >>> def testuni(val):
  865.         ...     for entry in val:
  866.         ...         if not isinstance(entry, unicode):
  867.         ...             print >> sys.stderr, type(entry)
  868.         ...             raise AssertionError, 'decode failed.'
  869.         ...         if isinstance(val[entry], dict):
  870.         ...             testuni(val[entry])
  871.         ...         elif not isinstance(val[entry], unicode):
  872.         ...             raise AssertionError, 'decode failed.'
  873.         >>> testuni(m)
  874.         >>> m.encode('ascii')
  875.         >>> a == m
  876.         1
  877.         """
  878.         warn('use of ``decode`` is deprecated.', DeprecationWarning)
  879.         
  880.         def decode(section, key, encoding = encoding, warn = True):
  881.             ''' '''
  882.             val = section[key]
  883.             if isinstance(val, (list, tuple)):
  884.                 newval = []
  885.                 for entry in val:
  886.                     newval.append(entry.decode(encoding))
  887.                 
  888.             elif isinstance(val, dict):
  889.                 newval = val
  890.             else:
  891.                 newval = val.decode(encoding)
  892.             newkey = key.decode(encoding)
  893.             section.rename(key, newkey)
  894.             section[newkey] = newval
  895.  
  896.         self.walk(decode, call_on_sections = True)
  897.  
  898.     
  899.     def encode(self, encoding):
  900.         '''
  901.         Encode all strings and values from unicode,
  902.         using the specified encoding.
  903.         
  904.         Works with subsections and list values.
  905.         Uses the ``walk`` method.
  906.         '''
  907.         warn('use of ``encode`` is deprecated.', DeprecationWarning)
  908.         
  909.         def encode(section, key, encoding = encoding):
  910.             ''' '''
  911.             val = section[key]
  912.             if isinstance(val, (list, tuple)):
  913.                 newval = []
  914.                 for entry in val:
  915.                     newval.append(entry.encode(encoding))
  916.                 
  917.             elif isinstance(val, dict):
  918.                 newval = val
  919.             else:
  920.                 newval = val.encode(encoding)
  921.             newkey = key.encode(encoding)
  922.             section.rename(key, newkey)
  923.             section[newkey] = newval
  924.  
  925.         self.walk(encode, call_on_sections = True)
  926.  
  927.     
  928.     def istrue(self, key):
  929.         '''A deprecated version of ``as_bool``.'''
  930.         warn('use of ``istrue`` is deprecated. Use ``as_bool`` method instead.', DeprecationWarning)
  931.         return self.as_bool(key)
  932.  
  933.     
  934.     def as_bool(self, key):
  935.         '''
  936.         Accepts a key as input. The corresponding value must be a string or
  937.         the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
  938.         retain compatibility with Python 2.2.
  939.         
  940.         If the string is one of  ``True``, ``On``, ``Yes``, or ``1`` it returns 
  941.         ``True``.
  942.         
  943.         If the string is one of  ``False``, ``Off``, ``No``, or ``0`` it returns 
  944.         ``False``.
  945.         
  946.         ``as_bool`` is not case sensitive.
  947.         
  948.         Any other input will raise a ``ValueError``.
  949.         
  950.         >>> a = ConfigObj()
  951.         >>> a[\'a\'] = \'fish\'
  952.         >>> a.as_bool(\'a\')
  953.         Traceback (most recent call last):
  954.         ValueError: Value "fish" is neither True nor False
  955.         >>> a[\'b\'] = \'True\'
  956.         >>> a.as_bool(\'b\')
  957.         1
  958.         >>> a[\'b\'] = \'off\'
  959.         >>> a.as_bool(\'b\')
  960.         0
  961.         '''
  962.         val = self[key]
  963.         if val == True:
  964.             return True
  965.         if val == False:
  966.             return False
  967.         
  968.         try:
  969.             if not isinstance(val, StringTypes):
  970.                 raise KeyError()
  971.             isinstance(val, StringTypes)
  972.             return self.main._bools[val.lower()]
  973.         except KeyError:
  974.             val == False
  975.             val == False
  976.             val == True
  977.             raise ValueError('Value "%s" is neither True nor False' % val)
  978.         except:
  979.             val == False
  980.  
  981.  
  982.     
  983.     def as_int(self, key):
  984.         """
  985.         A convenience method which coerces the specified value to an integer.
  986.         
  987.         If the value is an invalid literal for ``int``, a ``ValueError`` will
  988.         be raised.
  989.         
  990.         >>> a = ConfigObj()
  991.         >>> a['a'] = 'fish'
  992.         >>> a.as_int('a')
  993.         Traceback (most recent call last):
  994.         ValueError: invalid literal for int(): fish
  995.         >>> a['b'] = '1'
  996.         >>> a.as_int('b')
  997.         1
  998.         >>> a['b'] = '3.2'
  999.         >>> a.as_int('b')
  1000.         Traceback (most recent call last):
  1001.         ValueError: invalid literal for int(): 3.2
  1002.         """
  1003.         return int(self[key])
  1004.  
  1005.     
  1006.     def as_float(self, key):
  1007.         """
  1008.         A convenience method which coerces the specified value to a float.
  1009.         
  1010.         If the value is an invalid literal for ``float``, a ``ValueError`` will
  1011.         be raised.
  1012.         
  1013.         >>> a = ConfigObj()
  1014.         >>> a['a'] = 'fish'
  1015.         >>> a.as_float('a')
  1016.         Traceback (most recent call last):
  1017.         ValueError: invalid literal for float(): fish
  1018.         >>> a['b'] = '1'
  1019.         >>> a.as_float('b')
  1020.         1.0
  1021.         >>> a['b'] = '3.2'
  1022.         >>> a.as_float('b')
  1023.         3.2000000000000002
  1024.         """
  1025.         return float(self[key])
  1026.  
  1027.     
  1028.     def restore_default(self, key):
  1029.         '''
  1030.         Restore (and return) default value for the specified key.
  1031.         
  1032.         This method will only work for a ConfigObj that was created
  1033.         with a configspec and has been validated.
  1034.         
  1035.         If there is no default value for this key, ``KeyError`` is raised.
  1036.         '''
  1037.         default = self.default_values[key]
  1038.         dict.__setitem__(self, key, default)
  1039.         if key not in self.defaults:
  1040.             self.defaults.append(key)
  1041.         
  1042.         return default
  1043.  
  1044.     
  1045.     def restore_defaults(self):
  1046.         """
  1047.         Recursively restore default values to all members
  1048.         that have them.
  1049.         
  1050.         This method will only work for a ConfigObj that was created
  1051.         with a configspec and has been validated.
  1052.         
  1053.         It doesn't delete or modify entries without default values.
  1054.         """
  1055.         for key in self.default_values:
  1056.             self.restore_default(key)
  1057.         
  1058.         for section in self.sections:
  1059.             self[section].restore_defaults()
  1060.         
  1061.  
  1062.  
  1063.  
  1064. class ConfigObj(Section):
  1065.     '''An object to read, create, and write config files.'''
  1066.     _keyword = re.compile('^ # line start\n        (\\s*)                   # indentation\n        (                       # keyword\n            (?:".*?")|          # double quotes\n            (?:\'.*?\')|          # single quotes\n            (?:[^\'"=].*?)       # no quotes\n        )\n        \\s*=\\s*                 # divider\n        (.*)                    # value (including list values and comments)\n        $   # line end\n        ', re.VERBOSE)
  1067.     _sectionmarker = re.compile('^\n        (\\s*)                     # 1: indentation\n        ((?:\\[\\s*)+)              # 2: section marker open\n        (                         # 3: section name open\n            (?:"\\s*\\S.*?\\s*")|    # at least one non-space with double quotes\n            (?:\'\\s*\\S.*?\\s*\')|    # at least one non-space with single quotes\n            (?:[^\'"\\s].*?)        # at least one non-space unquoted\n        )                         # section name close\n        ((?:\\s*\\])+)              # 4: section marker close\n        \\s*(\\#.*)?                # 5: optional comment\n        $', re.VERBOSE)
  1068.     _valueexp = re.compile('^\n        (?:\n            (?:\n                (\n                    (?:\n                        (?:\n                            (?:".*?")|              # double quotes\n                            (?:\'.*?\')|              # single quotes\n                            (?:[^\'",\\#][^,\\#]*?)    # unquoted\n                        )\n                        \\s*,\\s*                     # comma\n                    )*      # match all list items ending in a comma (if any)\n                )\n                (\n                    (?:".*?")|                      # double quotes\n                    (?:\'.*?\')|                      # single quotes\n                    (?:[^\'",\\#\\s][^,]*?)|           # unquoted\n                    (?:(?<!,))                      # Empty value\n                )?          # last item in a list - or string value\n            )|\n            (,)             # alternatively a single comma - empty list\n        )\n        \\s*(\\#.*)?          # optional comment\n        $', re.VERBOSE)
  1069.     _listvalueexp = re.compile('\n        (\n            (?:".*?")|          # double quotes\n            (?:\'.*?\')|          # single quotes\n            (?:[^\'",\\#].*?)       # unquoted\n        )\n        \\s*,\\s*                 # comma\n        ', re.VERBOSE)
  1070.     _nolistvalue = re.compile('^\n        (\n            (?:".*?")|          # double quotes\n            (?:\'.*?\')|          # single quotes\n            (?:[^\'"\\#].*?)|     # unquoted\n            (?:)                # Empty value\n        )\n        \\s*(\\#.*)?              # optional comment\n        $', re.VERBOSE)
  1071.     _single_line_single = re.compile("^'''(.*?)'''\\s*(#.*)?$")
  1072.     _single_line_double = re.compile('^"""(.*?)"""\\s*(#.*)?$')
  1073.     _multi_line_single = re.compile("^(.*?)'''\\s*(#.*)?$")
  1074.     _multi_line_double = re.compile('^(.*?)"""\\s*(#.*)?$')
  1075.     _triple_quote = {
  1076.         "'''": (_single_line_single, _multi_line_single),
  1077.         '"""': (_single_line_double, _multi_line_double) }
  1078.     _bools = {
  1079.         'yes': True,
  1080.         'no': False,
  1081.         'on': True,
  1082.         'off': False,
  1083.         '1': True,
  1084.         '0': False,
  1085.         'true': True,
  1086.         'false': False }
  1087.     
  1088.     def __init__(self, infile = None, options = None, **kwargs):
  1089.         '''
  1090.         Parse a config file or create a config file object.
  1091.         
  1092.         ``ConfigObj(infile=None, options=None, **kwargs)``
  1093.         '''
  1094.         Section.__init__(self, self, 0, self)
  1095.         if infile is None:
  1096.             infile = []
  1097.         
  1098.         if options is None:
  1099.             options = { }
  1100.         else:
  1101.             options = dict(options)
  1102.         options.update(kwargs)
  1103.         defaults = OPTION_DEFAULTS.copy()
  1104.         for entry in options:
  1105.             if entry not in defaults:
  1106.                 raise TypeError('Unrecognised option "%s".' % entry)
  1107.             entry not in defaults
  1108.         
  1109.         defaults.update(options)
  1110.         self._initialise(defaults)
  1111.         configspec = defaults['configspec']
  1112.         self._original_configspec = configspec
  1113.         self._load(infile, configspec)
  1114.  
  1115.     
  1116.     def _load(self, infile, configspec):
  1117.         if isinstance(infile, StringTypes):
  1118.             self.filename = infile
  1119.             if os.path.isfile(infile):
  1120.                 h = open(infile, 'rb')
  1121.                 if not h.read():
  1122.                     pass
  1123.                 infile = []
  1124.                 h.close()
  1125.             elif self.file_error:
  1126.                 raise IOError('Config file not found: "%s".' % self.filename)
  1127.             elif self.create_empty:
  1128.                 h = open(infile, 'w')
  1129.                 h.write('')
  1130.                 h.close()
  1131.             
  1132.             infile = []
  1133.         elif isinstance(infile, (list, tuple)):
  1134.             infile = list(infile)
  1135.         elif isinstance(infile, dict):
  1136.             if isinstance(infile, ConfigObj):
  1137.                 infile = infile.dict()
  1138.             
  1139.             for entry in infile:
  1140.                 self[entry] = infile[entry]
  1141.             
  1142.             del self._errors
  1143.             if configspec is not None:
  1144.                 self._handle_configspec(configspec)
  1145.             else:
  1146.                 self.configspec = None
  1147.             return None
  1148.         if hasattr(infile, 'read'):
  1149.             if not infile.read():
  1150.                 pass
  1151.             infile = []
  1152.         else:
  1153.             raise TypeError('infile must be a filename, file like object, or list of lines.')
  1154.         self._parse(infile)
  1155.         if self._errors:
  1156.             info = 'at line %s.' % self._errors[0].line_number
  1157.             if len(self._errors) > 1:
  1158.                 msg = 'Parsing failed with several errors.\nFirst error %s' % info
  1159.                 error = ConfigObjError(msg)
  1160.             else:
  1161.                 error = self._errors[0]
  1162.             error.errors = self._errors
  1163.             error.config = self
  1164.             raise error
  1165.         self._errors
  1166.         del self._errors
  1167.         if configspec is None:
  1168.             self.configspec = None
  1169.         else:
  1170.             self._handle_configspec(configspec)
  1171.  
  1172.     
  1173.     def _initialise(self, options = None):
  1174.         if options is None:
  1175.             options = OPTION_DEFAULTS
  1176.         
  1177.         self.filename = None
  1178.         self._errors = []
  1179.         self.raise_errors = options['raise_errors']
  1180.         self.interpolation = options['interpolation']
  1181.         self.list_values = options['list_values']
  1182.         self.create_empty = options['create_empty']
  1183.         self.file_error = options['file_error']
  1184.         self.stringify = options['stringify']
  1185.         self.indent_type = options['indent_type']
  1186.         self.encoding = options['encoding']
  1187.         self.default_encoding = options['default_encoding']
  1188.         self.BOM = False
  1189.         self.newlines = None
  1190.         self.write_empty_values = options['write_empty_values']
  1191.         self.unrepr = options['unrepr']
  1192.         self.initial_comment = []
  1193.         self.final_comment = []
  1194.         self.configspec = { }
  1195.         Section._initialise(self)
  1196.  
  1197.     
  1198.     def __repr__(self):
  1199.         return [] % []([ '%s: %s' % (repr(key), repr(self[key])) for key in self.scalars + self.sections ])
  1200.  
  1201.     
  1202.     def _handle_bom(self, infile):
  1203.         """
  1204.         Handle any BOM, and decode if necessary.
  1205.         
  1206.         If an encoding is specified, that *must* be used - but the BOM should
  1207.         still be removed (and the BOM attribute set).
  1208.         
  1209.         (If the encoding is wrongly specified, then a BOM for an alternative
  1210.         encoding won't be discovered or removed.)
  1211.         
  1212.         If an encoding is not specified, UTF8 or UTF16 BOM will be detected and
  1213.         removed. The BOM attribute will be set. UTF16 will be decoded to
  1214.         unicode.
  1215.         
  1216.         NOTE: This method must not be called with an empty ``infile``.
  1217.         
  1218.         Specifying the *wrong* encoding is likely to cause a
  1219.         ``UnicodeDecodeError``.
  1220.         
  1221.         ``infile`` must always be returned as a list of lines, but may be
  1222.         passed in as a single string.
  1223.         """
  1224.         if self.encoding is not None and self.encoding.lower() not in BOM_LIST:
  1225.             return self._decode(infile, self.encoding)
  1226.         if isinstance(infile, (list, tuple)):
  1227.             line = infile[0]
  1228.         else:
  1229.             line = infile
  1230.         if self.encoding is not None:
  1231.             enc = BOM_LIST[self.encoding.lower()]
  1232.             if enc == 'utf_16':
  1233.                 for encoding, final_encoding in BOMS.items():
  1234.                     if not final_encoding:
  1235.                         continue
  1236.                     
  1237.                     if infile.startswith(BOM):
  1238.                         return self._decode(infile, encoding)
  1239.                 
  1240.                 return self._decode(infile, self.encoding)
  1241.             BOM = BOM_SET[enc]
  1242.             if not line.startswith(BOM):
  1243.                 return self._decode(infile, self.encoding)
  1244.             newline = line[len(BOM):]
  1245.             self.BOM = True
  1246.             return self._decode(infile, self.encoding)
  1247.         for encoding, final_encoding in BOMS.items():
  1248.             if not line.startswith(BOM):
  1249.                 continue
  1250.                 continue
  1251.             self.encoding = final_encoding
  1252.             if not final_encoding:
  1253.                 self.BOM = True
  1254.                 newline = line[len(BOM):]
  1255.                 if isinstance(infile, (list, tuple)):
  1256.                     infile[0] = newline
  1257.                 else:
  1258.                     infile = newline
  1259.                 if isinstance(infile, StringTypes):
  1260.                     return infile.splitlines(True)
  1261.                 return infile
  1262.             final_encoding
  1263.             return self._decode(infile, encoding)
  1264.         
  1265.         if isinstance(infile, StringTypes):
  1266.             return infile.splitlines(True)
  1267.         return infile
  1268.  
  1269.     
  1270.     def _a_to_u(self, aString):
  1271.         '''Decode ASCII strings to unicode if a self.encoding is specified.'''
  1272.         if self.encoding:
  1273.             return aString.decode('ascii')
  1274.         return aString
  1275.  
  1276.     
  1277.     def _decode(self, infile, encoding):
  1278.         '''
  1279.         Decode infile to unicode. Using the specified encoding.
  1280.         
  1281.         if is a string, it also needs converting to a list.
  1282.         '''
  1283.         if isinstance(infile, StringTypes):
  1284.             return infile.decode(encoding).splitlines(True)
  1285.         for i, line in enumerate(infile):
  1286.             if not isinstance(line, unicode):
  1287.                 infile[i] = line.decode(encoding)
  1288.                 continue
  1289.             isinstance(infile, StringTypes)
  1290.         
  1291.         return infile
  1292.  
  1293.     
  1294.     def _decode_element(self, line):
  1295.         '''Decode element to unicode if necessary.'''
  1296.         if not self.encoding:
  1297.             return line
  1298.         if isinstance(line, str) and self.default_encoding:
  1299.             return line.decode(self.default_encoding)
  1300.         return line
  1301.  
  1302.     
  1303.     def _str(self, value):
  1304.         '''
  1305.         Used by ``stringify`` within validate, to turn non-string values
  1306.         into strings.
  1307.         '''
  1308.         if not isinstance(value, StringTypes):
  1309.             return str(value)
  1310.         return value
  1311.  
  1312.     
  1313.     def _parse(self, infile):
  1314.         '''Actually parse the config file.'''
  1315.         temp_list_values = self.list_values
  1316.         if self.unrepr:
  1317.             self.list_values = False
  1318.         
  1319.         comment_list = []
  1320.         done_start = False
  1321.         this_section = self
  1322.         maxline = len(infile) - 1
  1323.         cur_index = -1
  1324.         reset_comment = False
  1325.         while cur_index < maxline:
  1326.             if reset_comment:
  1327.                 comment_list = []
  1328.             
  1329.             cur_index += 1
  1330.             line = infile[cur_index]
  1331.             sline = line.strip()
  1332.             if not sline or sline.startswith('#'):
  1333.                 reset_comment = False
  1334.                 comment_list.append(line)
  1335.                 continue
  1336.             
  1337.             if not done_start:
  1338.                 self.initial_comment = comment_list
  1339.                 comment_list = []
  1340.                 done_start = True
  1341.             
  1342.             reset_comment = True
  1343.             mat = self._sectionmarker.match(line)
  1344.             if mat is not None:
  1345.                 (indent, sect_open, sect_name, sect_close, comment) = mat.groups()
  1346.                 if indent and self.indent_type is None:
  1347.                     self.indent_type = indent
  1348.                 
  1349.                 cur_depth = sect_open.count('[')
  1350.                 if cur_depth != sect_close.count(']'):
  1351.                     self._handle_error('Cannot compute the section depth at line %s.', NestingError, infile, cur_index)
  1352.                     continue
  1353.                 
  1354.                 if cur_depth < this_section.depth:
  1355.                     
  1356.                     try:
  1357.                         parent = self._match_depth(this_section, cur_depth).parent
  1358.                     except SyntaxError:
  1359.                         self._handle_error('Cannot compute nesting level at line %s.', NestingError, infile, cur_index)
  1360.                         continue
  1361.                     except:
  1362.                         None<EXCEPTION MATCH>SyntaxError
  1363.                     
  1364.  
  1365.                 None<EXCEPTION MATCH>SyntaxError
  1366.                 if cur_depth == this_section.depth:
  1367.                     parent = this_section.parent
  1368.                 elif cur_depth == this_section.depth + 1:
  1369.                     parent = this_section
  1370.                 else:
  1371.                     self._handle_error('Section too nested at line %s.', NestingError, infile, cur_index)
  1372.                 sect_name = self._unquote(sect_name)
  1373.                 if parent.has_key(sect_name):
  1374.                     self._handle_error('Duplicate section name at line %s.', DuplicateError, infile, cur_index)
  1375.                     continue
  1376.                 
  1377.                 this_section = Section(parent, cur_depth, self, name = sect_name)
  1378.                 parent[sect_name] = this_section
  1379.                 parent.inline_comments[sect_name] = comment
  1380.                 parent.comments[sect_name] = comment_list
  1381.                 continue
  1382.             
  1383.             mat = self._keyword.match(line)
  1384.             if mat is None:
  1385.                 self._handle_error('Invalid line at line "%s".', ParseError, infile, cur_index)
  1386.                 continue
  1387.             (indent, key, value) = mat.groups()
  1388.             if indent and self.indent_type is None:
  1389.                 self.indent_type = indent
  1390.             
  1391.             if value[:3] in ('"""', "'''"):
  1392.                 
  1393.                 try:
  1394.                     (value, comment, cur_index) = self._multiline(value, infile, cur_index, maxline)
  1395.                 except SyntaxError:
  1396.                     self._handle_error('Parse error in value at line %s.', ParseError, infile, cur_index)
  1397.                     continue
  1398.  
  1399.                 if self.unrepr:
  1400.                     comment = ''
  1401.                     
  1402.                     try:
  1403.                         value = unrepr(value)
  1404.                     except Exception:
  1405.                         e = None
  1406.                         if type(e) == UnknownType:
  1407.                             msg = 'Unknown name or type in value at line %s.'
  1408.                         else:
  1409.                             msg = 'Parse error in value at line %s.'
  1410.                         self._handle_error(msg, UnreprError, infile, cur_index)
  1411.                         continue
  1412.                     except:
  1413.                         None<EXCEPTION MATCH>Exception
  1414.                     
  1415.  
  1416.                 None<EXCEPTION MATCH>Exception
  1417.             elif self.unrepr:
  1418.                 comment = ''
  1419.                 
  1420.                 try:
  1421.                     value = unrepr(value)
  1422.                 except Exception:
  1423.                     e = None
  1424.                     if isinstance(e, UnknownType):
  1425.                         msg = 'Unknown name or type in value at line %s.'
  1426.                     else:
  1427.                         msg = 'Parse error in value at line %s.'
  1428.                     self._handle_error(msg, UnreprError, infile, cur_index)
  1429.                     continue
  1430.                 except:
  1431.                     None<EXCEPTION MATCH>Exception
  1432.                 
  1433.  
  1434.             None<EXCEPTION MATCH>Exception
  1435.             
  1436.             try:
  1437.                 (value, comment) = self._handle_value(value)
  1438.             except SyntaxError:
  1439.                 self._handle_error('Parse error in value at line %s.', ParseError, infile, cur_index)
  1440.                 continue
  1441.  
  1442.             key = self._unquote(key)
  1443.             if this_section.has_key(key):
  1444.                 self._handle_error('Duplicate keyword name at line %s.', DuplicateError, infile, cur_index)
  1445.                 continue
  1446.             
  1447.             this_section.__setitem__(key, value, unrepr = True)
  1448.             this_section.inline_comments[key] = comment
  1449.             this_section.comments[key] = comment_list
  1450.             continue
  1451.         if self.indent_type is None:
  1452.             self.indent_type = ''
  1453.         
  1454.         if not self and not (self.initial_comment):
  1455.             self.initial_comment = comment_list
  1456.         elif not reset_comment:
  1457.             self.final_comment = comment_list
  1458.         
  1459.         self.list_values = temp_list_values
  1460.  
  1461.     
  1462.     def _match_depth(self, sect, depth):
  1463.         '''
  1464.         Given a section and a depth level, walk back through the sections
  1465.         parents to see if the depth level matches a previous section.
  1466.         
  1467.         Return a reference to the right section,
  1468.         or raise a SyntaxError.
  1469.         '''
  1470.         while depth < sect.depth:
  1471.             if sect is sect.parent:
  1472.                 raise SyntaxError()
  1473.             sect is sect.parent
  1474.             sect = sect.parent
  1475.         if sect.depth == depth:
  1476.             return sect
  1477.         raise SyntaxError()
  1478.  
  1479.     
  1480.     def _handle_error(self, text, ErrorClass, infile, cur_index):
  1481.         '''
  1482.         Handle an error according to the error settings.
  1483.         
  1484.         Either raise the error or store it.
  1485.         The error will have occured at ``cur_index``
  1486.         '''
  1487.         line = infile[cur_index]
  1488.         cur_index += 1
  1489.         message = text % cur_index
  1490.         error = ErrorClass(message, cur_index, line)
  1491.         if self.raise_errors:
  1492.             raise error
  1493.         self.raise_errors
  1494.         self._errors.append(error)
  1495.  
  1496.     
  1497.     def _unquote(self, value):
  1498.         '''Return an unquoted version of a value'''
  1499.         if value[0] == value[-1] and value[0] in ('"', "'"):
  1500.             value = value[1:-1]
  1501.         
  1502.         return value
  1503.  
  1504.     
  1505.     def _quote(self, value, multiline = True):
  1506.         """
  1507.         Return a safely quoted version of a value.
  1508.         
  1509.         Raise a ConfigObjError if the value cannot be safely quoted.
  1510.         If multiline is ``True`` (default) then use triple quotes
  1511.         if necessary.
  1512.         
  1513.         Don't quote values that don't need it.
  1514.         Recursively quote members of a list and return a comma joined list.
  1515.         Multiline is ``False`` for lists.
  1516.         Obey list syntax for empty and single member lists.
  1517.         
  1518.         If ``list_values=False`` then the value is only quoted if it contains
  1519.         a ``
  1520. `` (is multiline) or '#'.
  1521.         
  1522.         If ``write_empty_values`` is set, and the value is an empty string, it
  1523.         won't be quoted.
  1524.         """
  1525.         if multiline and self.write_empty_values and value == '':
  1526.             return ''
  1527.         if multiline and isinstance(value, (list, tuple)):
  1528.             if not value:
  1529.                 return ','
  1530.             if len(value) == 1:
  1531.                 return self._quote(value[0], multiline = False) + ','
  1532.             return []([ self._quote(val, multiline = False) for val in value ])
  1533.         if not isinstance(value, StringTypes):
  1534.             if self.stringify:
  1535.                 value = str(value)
  1536.             else:
  1537.                 raise TypeError('Value "%s" is not a string.' % value)
  1538.         self.stringify
  1539.         if not value:
  1540.             return '""'
  1541.         if not (self.list_values) and '\n' not in value:
  1542.             pass
  1543.         no_lists_no_quotes = '#' not in value
  1544.         if multiline:
  1545.             if not "'" in value or '"' in value:
  1546.                 pass
  1547.         need_triple = '\n' in value
  1548.         if multiline and not need_triple and "'" in value and '"' in value:
  1549.             pass
  1550.         hash_triple_quote = '#' in value
  1551.         if no_lists_no_quotes or not need_triple:
  1552.             pass
  1553.         check_for_single = not hash_triple_quote
  1554.         if quot == noquot and '#' in value and self.list_values:
  1555.             quot = self._get_single_quote(value)
  1556.         
  1557.         return quot % value
  1558.  
  1559.     
  1560.     def _get_single_quote(self, value):
  1561.         if "'" in value and '"' in value:
  1562.             raise ConfigObjError('Value "%s" cannot be safely quoted.' % value)
  1563.         '"' in value
  1564.         if '"' in value:
  1565.             quot = squot
  1566.         else:
  1567.             quot = dquot
  1568.         return quot
  1569.  
  1570.     
  1571.     def _get_triple_quote(self, value):
  1572.         if value.find('"""') != -1 and value.find("'''") != -1:
  1573.             raise ConfigObjError('Value "%s" cannot be safely quoted.' % value)
  1574.         value.find("'''") != -1
  1575.         if value.find('"""') == -1:
  1576.             quot = tdquot
  1577.         else:
  1578.             quot = tsquot
  1579.         return quot
  1580.  
  1581.     
  1582.     def _handle_value(self, value):
  1583.         '''
  1584.         Given a value string, unquote, remove comment,
  1585.         handle lists. (including empty and single member lists)
  1586.         '''
  1587.         if not self.list_values:
  1588.             mat = self._nolistvalue.match(value)
  1589.             if mat is None:
  1590.                 raise SyntaxError()
  1591.             mat is None
  1592.             return mat.groups()
  1593.         mat = self._valueexp.match(value)
  1594.         if mat is None:
  1595.             raise SyntaxError()
  1596.         mat is None
  1597.         (list_values, single, empty_list, comment) = mat.groups()
  1598.         if list_values == '' and single is None:
  1599.             raise SyntaxError()
  1600.         single is None
  1601.         if empty_list is not None:
  1602.             return ([], comment)
  1603.         if list_values == '':
  1604.             return (single, comment)
  1605.         the_list = self._listvalueexp.findall(list_values)
  1606.         the_list = [ self._unquote(val) for val in the_list ]
  1607.         return (the_list, comment)
  1608.  
  1609.     
  1610.     def _multiline(self, value, infile, cur_index, maxline):
  1611.         '''Extract the value, where we are in a multiline situation.'''
  1612.         quot = value[:3]
  1613.         newvalue = value[3:]
  1614.         single_line = self._triple_quote[quot][0]
  1615.         multi_line = self._triple_quote[quot][1]
  1616.         mat = single_line.match(value)
  1617.         if mat is not None:
  1618.             retval = list(mat.groups())
  1619.             retval.append(cur_index)
  1620.             return retval
  1621.         if newvalue.find(quot) != -1:
  1622.             raise SyntaxError()
  1623.         newvalue.find(quot) != -1
  1624.         while cur_index < maxline:
  1625.             cur_index += 1
  1626.             newvalue += '\n'
  1627.             line = infile[cur_index]
  1628.             if line.find(quot) == -1:
  1629.                 newvalue += line
  1630.                 continue
  1631.             mat is not None
  1632.             break
  1633.         raise SyntaxError()
  1634.         mat = multi_line.match(line)
  1635.         if mat is None:
  1636.             raise SyntaxError()
  1637.         mat is None
  1638.         (value, comment) = mat.groups()
  1639.         return (newvalue + value, comment, cur_index)
  1640.  
  1641.     
  1642.     def _handle_configspec(self, configspec):
  1643.         '''Parse the configspec.'''
  1644.         if not isinstance(configspec, ConfigObj):
  1645.             
  1646.             try:
  1647.                 configspec = ConfigObj(configspec, raise_errors = True, file_error = True, list_values = False)
  1648.             except ConfigObjError:
  1649.                 e = None
  1650.                 raise ConfigspecError('Parsing configspec failed: %s' % e)
  1651.             except IOError:
  1652.                 e = None
  1653.                 raise IOError('Reading configspec failed: %s' % e)
  1654.             except:
  1655.                 None<EXCEPTION MATCH>ConfigObjError
  1656.             
  1657.  
  1658.         None<EXCEPTION MATCH>ConfigObjError
  1659.         self._set_configspec_value(configspec, self)
  1660.  
  1661.     
  1662.     def _set_configspec_value(self, configspec, section):
  1663.         '''Used to recursively set configspec values.'''
  1664.         if '__many__' in configspec.sections:
  1665.             section.configspec['__many__'] = configspec['__many__']
  1666.             if len(configspec.sections) > 1:
  1667.                 raise RepeatSectionError()
  1668.             len(configspec.sections) > 1
  1669.         
  1670.         if hasattr(configspec, 'initial_comment'):
  1671.             section._configspec_initial_comment = configspec.initial_comment
  1672.             section._configspec_final_comment = configspec.final_comment
  1673.             section._configspec_encoding = configspec.encoding
  1674.             section._configspec_BOM = configspec.BOM
  1675.             section._configspec_newlines = configspec.newlines
  1676.             section._configspec_indent_type = configspec.indent_type
  1677.         
  1678.         for entry in configspec.scalars:
  1679.             section._configspec_comments[entry] = configspec.comments[entry]
  1680.             section._configspec_inline_comments[entry] = configspec.inline_comments[entry]
  1681.             section.configspec[entry] = configspec[entry]
  1682.             section._order.append(entry)
  1683.         
  1684.         for entry in configspec.sections:
  1685.             if entry == '__many__':
  1686.                 continue
  1687.             
  1688.             section._cs_section_comments[entry] = configspec.comments[entry]
  1689.             section._cs_section_inline_comments[entry] = configspec.inline_comments[entry]
  1690.             if not section.has_key(entry):
  1691.                 section[entry] = { }
  1692.             
  1693.             self._set_configspec_value(configspec[entry], section[entry])
  1694.         
  1695.  
  1696.     
  1697.     def _handle_repeat(self, section, configspec):
  1698.         '''Dynamically assign configspec for repeated section.'''
  1699.         
  1700.         try:
  1701.             section_keys = configspec.sections
  1702.             scalar_keys = configspec.scalars
  1703.         except AttributeError:
  1704.             section_keys = _[1]
  1705.             scalar_keys = _[2]
  1706.         except:
  1707.             []
  1708.  
  1709.         if '__many__' in section_keys and len(section_keys) > 1:
  1710.             raise RepeatSectionError()
  1711.         len(section_keys) > 1
  1712.         scalars = { }
  1713.         sections = { }
  1714.         for entry in scalar_keys:
  1715.             val = configspec[entry]
  1716.             scalars[entry] = val
  1717.         
  1718.         for entry in section_keys:
  1719.             val = configspec[entry]
  1720.             sections[entry] = val
  1721.         
  1722.         section.configspec = scalars
  1723.         for entry in sections:
  1724.             self._handle_repeat(section[entry], sections[entry])
  1725.         
  1726.  
  1727.     
  1728.     def _write_line(self, indent_string, entry, this_entry, comment):
  1729.         '''Write an individual line, for the write method'''
  1730.         if not self.unrepr:
  1731.             val = self._decode_element(self._quote(this_entry))
  1732.         else:
  1733.             val = repr(this_entry)
  1734.         return '%s%s%s%s%s' % (indent_string, self._decode_element(self._quote(entry, multiline = False)), self._a_to_u(' = '), val, self._decode_element(comment))
  1735.  
  1736.     
  1737.     def _write_marker(self, indent_string, depth, entry, comment):
  1738.         '''Write a section marker line'''
  1739.         return '%s%s%s%s%s' % (indent_string, self._a_to_u('[' * depth), self._quote(self._decode_element(entry), multiline = False), self._a_to_u(']' * depth), self._decode_element(comment))
  1740.  
  1741.     
  1742.     def _handle_comment(self, comment):
  1743.         '''Deal with a comment.'''
  1744.         if not comment:
  1745.             return ''
  1746.         start = self.indent_type
  1747.         if not comment.startswith('#'):
  1748.             start += self._a_to_u(' # ')
  1749.         
  1750.         return start + comment
  1751.  
  1752.     
  1753.     def write(self, outfile = None, section = None):
  1754.         """
  1755.         Write the current ConfigObj as a file
  1756.         
  1757.         tekNico: FIXME: use StringIO instead of real files
  1758.         
  1759.         >>> filename = a.filename
  1760.         >>> a.filename = 'test.ini'
  1761.         >>> a.write()
  1762.         >>> a.filename = filename
  1763.         >>> a == ConfigObj('test.ini', raise_errors=True)
  1764.         1
  1765.         """
  1766.         if self.indent_type is None:
  1767.             self.indent_type = DEFAULT_INDENT_TYPE
  1768.         
  1769.         out = []
  1770.         cs = self._a_to_u('#')
  1771.         csp = self._a_to_u('# ')
  1772.         if section is None:
  1773.             int_val = self.interpolation
  1774.             self.interpolation = False
  1775.             section = self
  1776.             for line in self.initial_comment:
  1777.                 line = self._decode_element(line)
  1778.                 stripped_line = line.strip()
  1779.                 if stripped_line and not stripped_line.startswith(cs):
  1780.                     line = csp + line
  1781.                 
  1782.                 out.append(line)
  1783.             
  1784.         
  1785.         indent_string = self.indent_type * section.depth
  1786.         for entry in section.scalars + section.sections:
  1787.             if entry in section.defaults:
  1788.                 continue
  1789.             
  1790.             for comment_line in section.comments[entry]:
  1791.                 comment_line = self._decode_element(comment_line.lstrip())
  1792.                 if comment_line and not comment_line.startswith(cs):
  1793.                     comment_line = csp + comment_line
  1794.                 
  1795.                 out.append(indent_string + comment_line)
  1796.             
  1797.             this_entry = section[entry]
  1798.             comment = self._handle_comment(section.inline_comments[entry])
  1799.             if isinstance(this_entry, dict):
  1800.                 out.append(self._write_marker(indent_string, this_entry.depth, entry, comment))
  1801.                 out.extend(self.write(section = this_entry))
  1802.                 continue
  1803.             out.append(self._write_line(indent_string, entry, this_entry, comment))
  1804.         
  1805.         if section is self:
  1806.             for line in self.final_comment:
  1807.                 line = self._decode_element(line)
  1808.                 stripped_line = line.strip()
  1809.                 if stripped_line and not stripped_line.startswith(cs):
  1810.                     line = csp + line
  1811.                 
  1812.                 out.append(line)
  1813.             
  1814.             self.interpolation = int_val
  1815.         
  1816.         if section is not self:
  1817.             return out
  1818.         if self.filename is None and outfile is None:
  1819.             if self.BOM:
  1820.                 pass
  1821.             return out
  1822.         if not self.newlines:
  1823.             pass
  1824.         newline = os.linesep
  1825.         output = self._a_to_u(newline).join(out)
  1826.         if self.BOM:
  1827.             if self.encoding is None or match_utf8(self.encoding):
  1828.                 output = BOM_UTF8 + output
  1829.             
  1830.         if not output.endswith(newline):
  1831.             output += newline
  1832.         
  1833.         if outfile is not None:
  1834.             outfile.write(output)
  1835.         else:
  1836.             h = open(self.filename, 'wb')
  1837.             h.write(output)
  1838.             h.close()
  1839.  
  1840.     
  1841.     def validate(self, validator, preserve_errors = False, copy = False, section = None):
  1842.         '''
  1843.         Test the ConfigObj against a configspec.
  1844.         
  1845.         It uses the ``validator`` object from *validate.py*.
  1846.         
  1847.         To run ``validate`` on the current ConfigObj, call: ::
  1848.         
  1849.             test = config.validate(validator)
  1850.         
  1851.         (Normally having previously passed in the configspec when the ConfigObj
  1852.         was created - you can dynamically assign a dictionary of checks to the
  1853.         ``configspec`` attribute of a section though).
  1854.         
  1855.         It returns ``True`` if everything passes, or a dictionary of
  1856.         pass/fails (True/False). If every member of a subsection passes, it
  1857.         will just have the value ``True``. (It also returns ``False`` if all
  1858.         members fail).
  1859.         
  1860.         In addition, it converts the values from strings to their native
  1861.         types if their checks pass (and ``stringify`` is set).
  1862.         
  1863.         If ``preserve_errors`` is ``True`` (``False`` is default) then instead
  1864.         of a marking a fail with a ``False``, it will preserve the actual
  1865.         exception object. This can contain info about the reason for failure.
  1866.         For example the ``VdtValueTooSmallError`` indicates that the value
  1867.         supplied was too small. If a value (or section) is missing it will
  1868.         still be marked as ``False``.
  1869.         
  1870.         You must have the validate module to use ``preserve_errors=True``.
  1871.         
  1872.         You can then use the ``flatten_errors`` function to turn your nested
  1873.         results dictionary into a flattened list of failures - useful for
  1874.         displaying meaningful error messages.
  1875.         '''
  1876.         if section is None:
  1877.             if self.configspec is None:
  1878.                 raise ValueError('No configspec supplied.')
  1879.             self.configspec is None
  1880.             if preserve_errors:
  1881.                 VdtMissingValue = VdtMissingValue
  1882.                 import validate
  1883.                 self._vdtMissingValue = VdtMissingValue
  1884.             
  1885.             section = self
  1886.         
  1887.         spec_section = section.configspec
  1888.         if copy and hasattr(section, '_configspec_initial_comment'):
  1889.             section.initial_comment = section._configspec_initial_comment
  1890.             section.final_comment = section._configspec_final_comment
  1891.             section.encoding = section._configspec_encoding
  1892.             section.BOM = section._configspec_BOM
  1893.             section.newlines = section._configspec_newlines
  1894.             section.indent_type = section._configspec_indent_type
  1895.         
  1896.         if '__many__' in section.configspec:
  1897.             many = spec_section['__many__']
  1898.             for entry in section.sections:
  1899.                 self._handle_repeat(section[entry], many)
  1900.             
  1901.         
  1902.         out = { }
  1903.         ret_true = True
  1904.         ret_false = True
  1905.         order = _[1]
  1906.         [] += _[2]
  1907.         for entry in order:
  1908.             
  1909.             try:
  1910.                 check = validator.check(spec_section[entry], val, missing = missing)
  1911.             except validator.baseErrorClass:
  1912.                 None if entry not in section.scalars or entry in section.defaults else []
  1913.                 e = None if entry not in section.scalars or entry in section.defaults else []
  1914.                 if not preserve_errors or isinstance(e, self._vdtMissingValue):
  1915.                     out[entry] = False
  1916.                 else:
  1917.                     out[entry] = e
  1918.                     ret_false = False
  1919.                 ret_true = False
  1920.                 continue
  1921.  
  1922.             
  1923.             try:
  1924.                 section.default_values.pop(entry, None)
  1925.             except AttributeError:
  1926.                 None if entry not in section.scalars or entry in section.defaults else []
  1927.                 None if entry not in section.scalars or entry in section.defaults else []
  1928.                 
  1929.                 try:
  1930.                     del section.default_values[entry]
  1931.                 except KeyError:
  1932.                     pass
  1933.                 except:
  1934.                     None<EXCEPTION MATCH>KeyError
  1935.                 
  1936.  
  1937.                 None<EXCEPTION MATCH>KeyError
  1938.  
  1939.             if hasattr(validator, 'get_default_value'):
  1940.                 
  1941.                 try:
  1942.                     section.default_values[entry] = validator.get_default_value(spec_section[entry])
  1943.                 except KeyError:
  1944.                     None if entry not in section.scalars or entry in section.defaults else []
  1945.                     None if entry not in section.scalars or entry in section.defaults else []
  1946.                 except:
  1947.                     None if entry not in section.scalars or entry in section.defaults else []<EXCEPTION MATCH>KeyError
  1948.                 
  1949.  
  1950.             None if entry not in section.scalars or entry in section.defaults else []
  1951.             ret_false = False
  1952.             out[entry] = True
  1953.             if self.stringify or missing:
  1954.                 if not self.stringify:
  1955.                     if isinstance(check, (list, tuple)):
  1956.                         check = [ self._str(item) for item in check ]
  1957.                     elif missing and check is None:
  1958.                         check = ''
  1959.                     else:
  1960.                         check = self._str(check)
  1961.                 
  1962.                 if check != val or missing:
  1963.                     section[entry] = check
  1964.                 
  1965.             
  1966.             if not copy and missing and entry not in section.defaults:
  1967.                 section.defaults.append(entry)
  1968.                 continue
  1969.         
  1970.         for entry in section.sections:
  1971.             if section is self and entry == 'DEFAULT':
  1972.                 continue
  1973.             
  1974.             if copy:
  1975.                 section.comments[entry] = section._cs_section_comments.get(entry, [])
  1976.                 section.inline_comments[entry] = section._cs_section_inline_comments.get(entry, '')
  1977.             
  1978.             check = self.validate(validator, preserve_errors = preserve_errors, copy = copy, section = section[entry])
  1979.             out[entry] = check
  1980.             if check == False:
  1981.                 ret_true = False
  1982.                 continue
  1983.             if check == True:
  1984.                 ret_false = False
  1985.                 continue
  1986.             ret_true = False
  1987.             ret_false = False
  1988.         
  1989.         if ret_true:
  1990.             return True
  1991.         if ret_false:
  1992.             return False
  1993.         return out
  1994.  
  1995.     
  1996.     def reset(self):
  1997.         """Clear ConfigObj instance and restore to 'freshly created' state."""
  1998.         self.clear()
  1999.         self._initialise()
  2000.         self.configspec = None
  2001.         self._original_configspec = None
  2002.  
  2003.     
  2004.     def reload(self):
  2005.         """
  2006.         Reload a ConfigObj from file.
  2007.         
  2008.         This method raises a ``ReloadError`` if the ConfigObj doesn't have
  2009.         a filename attribute pointing to a file.
  2010.         """
  2011.         if not isinstance(self.filename, StringTypes):
  2012.             raise ReloadError()
  2013.         isinstance(self.filename, StringTypes)
  2014.         filename = self.filename
  2015.         current_options = { }
  2016.         for entry in OPTION_DEFAULTS:
  2017.             if entry == 'configspec':
  2018.                 continue
  2019.             
  2020.             current_options[entry] = getattr(self, entry)
  2021.         
  2022.         configspec = self._original_configspec
  2023.         current_options['configspec'] = configspec
  2024.         self.clear()
  2025.         self._initialise(current_options)
  2026.         self._load(filename, configspec)
  2027.  
  2028.  
  2029.  
  2030. class SimpleVal(object):
  2031.     '''
  2032.     A simple validator.
  2033.     Can be used to check that all members expected are present.
  2034.     
  2035.     To use it, provide a configspec with all your members in (the value given
  2036.     will be ignored). Pass an instance of ``SimpleVal`` to the ``validate``
  2037.     method of your ``ConfigObj``. ``validate`` will return ``True`` if all
  2038.     members are present, or a dictionary with True/False meaning
  2039.     present/missing. (Whole missing sections will be replaced with ``False``)
  2040.     '''
  2041.     
  2042.     def __init__(self):
  2043.         self.baseErrorClass = ConfigObjError
  2044.  
  2045.     
  2046.     def check(self, check, member, missing = False):
  2047.         '''A dummy check method, always returns the value unchanged.'''
  2048.         if missing:
  2049.             raise self.baseErrorClass()
  2050.         missing
  2051.         return member
  2052.  
  2053.  
  2054.  
  2055. def flatten_errors(cfg, res, levels = None, results = None):
  2056.     '''
  2057.     An example function that will turn a nested dictionary of results
  2058.     (as returned by ``ConfigObj.validate``) into a flat list.
  2059.     
  2060.     ``cfg`` is the ConfigObj instance being checked, ``res`` is the results
  2061.     dictionary returned by ``validate``.
  2062.     
  2063.     (This is a recursive function, so you shouldn\'t use the ``levels`` or
  2064.     ``results`` arguments - they are used by the function.
  2065.     
  2066.     Returns a list of keys that failed. Each member of the list is a tuple :
  2067.     ::
  2068.     
  2069.         ([list of sections...], key, result)
  2070.     
  2071.     If ``validate`` was called with ``preserve_errors=False`` (the default)
  2072.     then ``result`` will always be ``False``.
  2073.  
  2074.     *list of sections* is a flattened list of sections that the key was found
  2075.     in.
  2076.     
  2077.     If the section was missing then key will be ``None``.
  2078.     
  2079.     If the value (or section) was missing then ``result`` will be ``False``.
  2080.     
  2081.     If ``validate`` was called with ``preserve_errors=True`` and a value
  2082.     was present, but failed the check, then ``result`` will be the exception
  2083.     object returned. You can use this as a string that describes the failure.
  2084.     
  2085.     For example *The value "3" is of the wrong type*.
  2086.     
  2087.     >>> import validate
  2088.     >>> vtor = validate.Validator()
  2089.     >>> my_ini = \'\'\'
  2090.     ...     option1 = True
  2091.     ...     [section1]
  2092.     ...     option1 = True
  2093.     ...     [section2]
  2094.     ...     another_option = Probably
  2095.     ...     [section3]
  2096.     ...     another_option = True
  2097.     ...     [[section3b]]
  2098.     ...     value = 3
  2099.     ...     value2 = a
  2100.     ...     value3 = 11
  2101.     ...     \'\'\'
  2102.     >>> my_cfg = \'\'\'
  2103.     ...     option1 = boolean()
  2104.     ...     option2 = boolean()
  2105.     ...     option3 = boolean(default=Bad_value)
  2106.     ...     [section1]
  2107.     ...     option1 = boolean()
  2108.     ...     option2 = boolean()
  2109.     ...     option3 = boolean(default=Bad_value)
  2110.     ...     [section2]
  2111.     ...     another_option = boolean()
  2112.     ...     [section3]
  2113.     ...     another_option = boolean()
  2114.     ...     [[section3b]]
  2115.     ...     value = integer
  2116.     ...     value2 = integer
  2117.     ...     value3 = integer(0, 10)
  2118.     ...         [[[section3b-sub]]]
  2119.     ...         value = string
  2120.     ...     [section4]
  2121.     ...     another_option = boolean()
  2122.     ...     \'\'\'
  2123.     >>> cs = my_cfg.split(\'\\n\')
  2124.     >>> ini = my_ini.split(\'\\n\')
  2125.     >>> cfg = ConfigObj(ini, configspec=cs)
  2126.     >>> res = cfg.validate(vtor, preserve_errors=True)
  2127.     >>> errors = []
  2128.     >>> for entry in flatten_errors(cfg, res):
  2129.     ...     section_list, key, error = entry
  2130.     ...     section_list.insert(0, \'[root]\')
  2131.     ...     if key is not None:
  2132.     ...        section_list.append(key)
  2133.     ...     else:
  2134.     ...         section_list.append(\'[missing]\')
  2135.     ...     section_string = \', \'.join(section_list)
  2136.     ...     errors.append((section_string, \' = \', error))
  2137.     >>> errors.sort()
  2138.     >>> for entry in errors:
  2139.     ...     print entry[0], entry[1], (entry[2] or 0)
  2140.     [root], option2  =  0
  2141.     [root], option3  =  the value "Bad_value" is of the wrong type.
  2142.     [root], section1, option2  =  0
  2143.     [root], section1, option3  =  the value "Bad_value" is of the wrong type.
  2144.     [root], section2, another_option  =  the value "Probably" is of the wrong type.
  2145.     [root], section3, section3b, section3b-sub, [missing]  =  0
  2146.     [root], section3, section3b, value2  =  the value "a" is of the wrong type.
  2147.     [root], section3, section3b, value3  =  the value "11" is too big.
  2148.     [root], section4, [missing]  =  0
  2149.     '''
  2150.     if levels is None:
  2151.         levels = []
  2152.         results = []
  2153.     
  2154.     if res is True:
  2155.         return results
  2156.     if res is False:
  2157.         results.append((levels[:], None, False))
  2158.         if levels:
  2159.             levels.pop()
  2160.         
  2161.         return results
  2162.     for key, val in res.items():
  2163.         if isinstance(cfg.get(key), dict):
  2164.             levels.append(key)
  2165.             flatten_errors(cfg[key], val, levels, results)
  2166.             continue
  2167.         
  2168.         results.append((levels[:], key, val))
  2169.     
  2170.     if levels:
  2171.         levels.pop()
  2172.     
  2173.     return results
  2174.  
  2175.